package com.frinder.base.utils;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.*;

/**
 * @author frinder
 * @date 2018/5/19
 * @Description: 线程池辅助类
 */
public class ThreadUtils {

    /**
     * 获取 single thread pool
     *
     * @return
     */
    public static ExecutorService getSingleThreadPoolExecutor(Runnable executor) {
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                .setNameFormat("single-thread-pool-%d").build();
        ExecutorService executorService = new ThreadPoolExecutor(
                1,
                1,
                0L,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(1024),
                namedThreadFactory,
                new ThreadPoolExecutor.AbortPolicy()
        );
        executorService.execute(executor);
        return executorService;
    }

    /**
     * 获取 single thread pool
     *
     * @return
     */
    public static ExecutorService getSingleThreadPoolExecutor(String threadName) {
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                .setNameFormat(threadName)
                .build();
        ExecutorService executorService = new ThreadPoolExecutor(
                1,
                1,
                0L,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(1024),
                namedThreadFactory,
                new ThreadPoolExecutor.AbortPolicy()
        );
        return executorService;
    }

    /**
     * 获取 thread pool
     *
     * @param poolSize 线程数
     * @return
     */
    public static ExecutorService getThreadPoolExecutor(int poolSize) {
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                .setNameFormat("single-thread-pool-%d").build();
        ExecutorService executorService = new ThreadPoolExecutor(
                poolSize,
                poolSize,
                30L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(1024),
                namedThreadFactory,
                new ThreadPoolExecutor.AbortPolicy()
        );
        return executorService;
    }

    /**
     * @Author frinder
     * @Description 睡一会
     * @Date 2019/2/3 11:09
     * @Param [delay]
     * @Return void
     */
    public static void sleep(long delay) {
        try {
            TimeUnit.MILLISECONDS.sleep(delay);
        } catch (Exception e) {
        }
    }

}
